<?php
class Xemay_items extends Model {
	private $data;
	function Xemay()
	{
		parent::Model();		
	}

	function getAllData() {
		$this -> data = array();
		$qresult = $this->db->get('xemay_item');
		foreach($qresult -> result() as $row) {
			array_push($this -> data,$row);
		}
	}

	function insertItems(
		$catid,
		$so_luong,
		$sk,$sm,
		$gia_nhap,$nguoi_nhap) {
		
		$this -> load -> helper('date');
		$datestring = "%Y/%m/%d";
		$today = mdate($datestring,now());
		
		for($i = 0; $i < $so_luong ; $i++ ) {
			$data = array (
			'SK' => $sk[$i],
			'SM' => $sm[$i],
			'CAT_ID' => $catid,
			'ngay_nhap' => $today,  
			'gia_nhap' => (int)(str_replace(",","",$gia_nhap)),
			'nguoi_nhap' => $nguoi_nhap,
			'da_ban' => 0
			);
			$this -> db -> insert('xemay_item',$data);
		}
	}

	/**
	 * Return whether sk/sm exists in db
	 * @param $sk
	 * @param $sm
	 * @param $da_ban Ref_Boolean type 
	 * @return unknown_type
	 */
	function existItem($sk,$sm,&$da_ban) {
		$da_ban = 1;
		$qresult = $this -> db -> 
			get_where('xemay_item',
				array(
					'SK'=>$sk,
					'SM'=>$sm			
			));
		$cnt = $qresult -> num_rows();
		if ( $cnt == 0 ) return false;
		$row = $qresult -> row();
		if ( $row -> DA_BAN == NULL) {
			$da_ban = 0;		
		}		
		return true;
	}
	
	function getSuggestedSellPrice($sk,$sm) {
		$query = $this 
		-> db -> select('cat_id') -> from('xemay_item')
		-> where(array('sk'=>$sk,'sm'=>$sm)) -> get(); 
		$catID = $query -> row() -> cat_id;
		$query = $this 
		-> db -> select('gia_xuat_chung') -> from('xemay_category')
		-> where('cat_id',$catID) -> get();		
		$suggestedSellPrice = $query -> row() -> gia_xuat_chung;
		return $suggestedSellPrice;	
	}
	
	function getRow($sk,$sm) {
		$query = $this -> db -> getwhere('xemay_item',array(
			'sk' => $sk,
			'sm' => $sm
		));
		if ($query -> num_rows() == 0 ) return null;
		return $query -> row();
	}
	
	function updateItemBySold($sk,$sm,$gia_xuat,$ngay_xuat,$nguoi_xuat) {
		$new_data = array (
		'GIA_XUAT' => $gia_xuat,
		'NGAY_XUAT' => $ngay_xuat,
		'NGUOI_XUAT'=> $nguoi_xuat,
		'DA_BAN' => true
		);
		$condition = array(
		'SK' => $sk,
		'SM' => $sm
		);
		$query = $this -> db -> update('xemay_item',$new_data,$condition);			
	}
}
?>